<template>
  <div>
    <!-- 顶部导航栏 - 修复布局一致性 -->
    <!-- <el-header class="custom-header">
      <div class="header-left">
        <span class="logo-title">作物标准象与象差知识库系统</span>
      </div>
   
    </el-header> -->

    <!-- 分类导航 - 和其他页面完全一致 -->
    <div>
      <el-menu :default-active="activeIndex" class="custom-menu" mode="horizontal" @select="handleMenuItemSelect">
        <el-menu-item index="1">首页</el-menu-item>
        <el-menu-item index="2">标准象百科</el-menu-item>
        <el-menu-item index="3">象差百科</el-menu-item>
        <el-menu-item index="4">知识检索</el-menu-item>
        <el-menu-item index="5">问答专区</el-menu-item>
      </el-menu>
    </div>

    <!-- 搜索区域 - 完全对齐其他页面的样式，增加智能提示 -->
    <div class="search-section">
      <div class="headline">知识检索 - 象差百科</div>
      
      <div class="search-bar">
        <!-- 🔥 新增：智能搜索提示框 -->
        <el-autocomplete
          v-model="searchKeyword"
          :fetch-suggestions="querySearchSuggestions"
          placeholder="请输入关键词"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
          @select="handleSuggestionSelect"
          :debounce="300"
          :trigger-on-focus="false"
          highlight-first-item
          value-key="value"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
          <template #default="{ item }">
            <div class="suggestion-item">
              <div class="suggestion-main">
                <span class="suggestion-name">{{ item.value }}</span>
                <el-tag :type="getSuggestionTagType(item.type)" size="small">
                  {{ item.type }}
                </el-tag>
              </div>
              <div class="suggestion-desc" v-if="item.description">{{ item.description }}</div>
            </div>
          </template>
          <template #append>
            <el-button type="primary" @click="handleSearch" style="font-size:20px;color:#409EFF">
              搜索
            </el-button>
          </template>
        </el-autocomplete>
      </div>
      
      <div class="hot-words">
        热门搜索：
        <el-link type="primary" @click="setKeyword('小麦赤霉病')">小麦赤霉病</el-link>
        <el-link type="primary" @click="setKeyword('玉米褐斑病')">玉米褐斑病</el-link>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content-section">
      <el-row :gutter="30">
        <!-- 左侧导航栏 -->
        <el-col :span="4" class="sidebar">
          <div class="sidebar-header">
            <h3>作物种类</h3>
          </div>

          <!-- 🔥 动态加载的作物分类菜单 -->
          <el-skeleton v-if="categoriesLoading" :rows="4" animated class="category-skeleton" />
          <el-menu 
            v-else 
            v-model:default-active="activeMenu" 
            :default-openeds="['禾本科']"
            class="sidebar-menu" 
            @select="handleMenuSelect"
          >
            <el-sub-menu v-for="(group, groupName) in groupedCategories" :key="groupName" :index="groupName">
              <template #title>
                <span>{{ groupName }}</span>
              </template>
              <el-menu-item v-for="category in group" :key="category.id" :index="`${groupName}-${category.id}`">
                {{ category.name }}
                <span class="category-count">({{ category.count }})</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-col>

        <!-- 右侧内容展示区域 -->
        <el-col :span="20" class="main-content">
          <div class="content-wrapper">

            <!-- 🔥 搜索结果展示 -->
            <div v-if="isSearchMode" class="search-results-section">
              <h2 class="section-header">
                搜索结果 ({{ searchResults.length }}) 项
                <el-button @click="clearSearch" type="text" class="clear-search">
                  <el-icon>
                    <Close />
                  </el-icon>
                  清除搜索
                </el-button>
              </h2>
              <el-empty v-if="searchResults.length === 0" description="未找到相关病虫害信息" />
              <div v-else class="pest-grid">
                <div v-for="item in searchResults" :key="item.id" class="pest-item" @click="goToSpecificDetail(item)">
                  <div class="pest-name">{{ item.name }}</div>
                  <el-tag :type="getTagType(item.type)" size="small">
                    {{ item.type }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 🔥 正常的分类展示 -->
            <div v-else>
              <!-- 病害展示区域 -->
              <div class="disease-section">
                <h2 class="section-header">
                  {{ currentCrop }}病害共有 ({{ diseaseCount }}) 种
                  <el-skeleton v-if="dataLoading" animated class="count-skeleton" />
                </h2>
                <el-skeleton v-if="dataLoading" :rows="2" animated />
                <div v-else-if="diseaseList.length === 0" class="empty-state">
                  <el-empty description="暂无病害数据" />
                </div>
                <div v-else class="pest-grid">
                  <div v-for="disease in diseaseList" :key="disease.id" class="pest-item"
                    @click="goToSpecificDetail(disease)">
                    {{ disease.name }}
                  </div>
                </div>
              </div>

              <!-- 虫害展示区域 -->
              <div class="pest-section">
                <h2 class="section-header">
                  {{ currentCrop }}虫害共有 ({{ pestCount }}) 种
                  <el-skeleton v-if="dataLoading" animated class="count-skeleton" />
                </h2>
                <el-skeleton v-if="dataLoading" :rows="2" animated />
                <div v-else-if="pestList.length === 0" class="empty-state">
                  <el-empty description="暂无虫害数据" />
                </div>
                <div v-else class="pest-grid">
                  <div v-for="pest in pestList" :key="pest.id" class="pest-item" @click="goToSpecificDetail(pest)">
                    {{ pest.name }}
                  </div>
                </div>
              </div>

              <!-- 🔥 生理性病害展示区域 -->
              <div class="physiological-disease-section">
                <h2 class="section-header">
                  {{ currentCrop }}生理性病害共有 ({{ physiologicalDiseaseCount }}) 种
                  <el-skeleton v-if="dataLoading" animated class="count-skeleton" />
                </h2>
                <el-skeleton v-if="dataLoading" :rows="2" animated />
                <div v-else-if="physiologicalDiseaseList.length === 0" class="empty-state">
                  <el-empty description="暂无生理性病害数据" />
                </div>
                <div v-else class="pest-grid">
                  <div v-for="physiologicalDisease in physiologicalDiseaseList" :key="physiologicalDisease.id"
                    class="pest-item" @click="goToSpecificDetail(physiologicalDisease)">
                    {{ physiologicalDisease.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Close, User, Search } from '@element-plus/icons-vue'

// 🔥 导入API函数
import {
  getPestDiseaseCategories,
  getPestDiseaseByCategory,
  searchPestDisease
} from '@/api/agriculture/guo/pestdisease/pestdisease'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

// 🔥 响应式数据
const searchKeyword = ref('')
const activeMenu = ref('禾本科-1') // 🔥 默认选中第一个小麦分类
const currentCrop = ref('小麦') // 🔥 默认显示小麦
const currentCategoryId = ref(null)

// 顶部菜单相关 - 修复路由映射
const activeIndex = ref('3') // 默认选中象差百科

// 🔥 加载状态
const categoriesLoading = ref(true)
const dataLoading = ref(false)
const searchLoading = ref(false)

// 🔥 数据存储
const categories = ref({})  // 作物分类数据
const pestData = ref({     // 当前显示的病虫害数据
  diseases: [],
  pests: [],
  physiologicalDiseases: [],
  diseaseCount: 0,
  pestCount: 0,
  physiologicalDiseaseCount: 0
})

// 🔥 搜索相关
const isSearchMode = ref(false)
const searchResults = ref([])
const searchSuggestions = ref([]) // 搜索建议缓存

// 🔥 修复路由列表映射
const routerList = [
  "",
  "CropIndex",                    // 1 - 首页
  "CropVarietyFront",             // 2 - 标准象百科
  "CropDiseasePest",         // 3 - 象差百科
  "CropGraph",               // 4 - 知识检索
  "QA"                       // 5 - 问答专区
];

// 🔥 计算属性 - 按组分类的分类数据
const groupedCategories = computed(() => {
  const groups = {}

  Object.entries(categories.value).forEach(([id, category]) => {
    let groupName = '其他'

    // 根据作物名称分组
    if (category.name.includes('小麦') || category.name.includes('玉米')) {
      groupName = '禾本科'
    } else if (category.name.includes('马铃薯') || category.name.includes('红薯')) {
      groupName = '薯类'
    } else if (category.name.includes('棉花') || category.name.includes('亚麻')) {
      groupName = '纤维类'
    }

    if (!groups[groupName]) {
      groups[groupName] = []
    }

    groups[groupName].push({
      id: id,
      name: category.name,
      count: category.count,
      diseases: category.diseases,
      pests: category.pests,
      physiologicalDiseases: category.physiologicalDiseases || 0
    })
  })

  return groups
})

// 🔥 计算属性 - 当前显示的数据
const diseaseList = computed(() => pestData.value.diseases || [])
const pestList = computed(() => pestData.value.pests || [])
const physiologicalDiseaseList = computed(() => pestData.value.physiologicalDiseases || [])
const diseaseCount = computed(() => pestData.value.diseaseCount || 0)
const pestCount = computed(() => pestData.value.pestCount || 0)
const physiologicalDiseaseCount = computed(() => pestData.value.physiologicalDiseaseCount || 0)

// 🔥 新增：智能搜索建议功能
const querySearchSuggestions = async (queryString, callback) => {
  if (!queryString || queryString.length < 1) {
    callback([])
    return
  }
  
  try {
    const suggestions = []
    const keyword = queryString.toLowerCase()
    
    // 🔥 方案1: 作物相关建议
    const crops = ['小麦', '玉米']
    crops.forEach(crop => {
      if (crop.includes(keyword) || keyword.includes(crop.charAt(0))) {
        suggestions.push({
          value: crop,
          type: '作物',
          description: `查看${crop}的所有病虫害信息`,
          category: 'crop'
        })
        
        // 添加组合建议
        suggestions.push({
          value: `${crop}病害`,
          type: '病害',
          description: `查看${crop}的所有病害`,
          category: 'disease'
        })
        
        suggestions.push({
          value: `${crop}虫害`,
          type: '虫害', 
          description: `查看${crop}的所有虫害`,
          category: 'pest'
        })
      }
    })
    
    // 🔥 方案2: 从当前数据中匹配
    const allCurrentData = [
      ...diseaseList.value,
      ...pestList.value,
      ...physiologicalDiseaseList.value
    ]
    
    allCurrentData.forEach(item => {
      if (item.name.toLowerCase().includes(keyword)) {
        suggestions.push({
          value: item.name,
          type: item.type,
          description: `${item.type} - 点击查看详情`,
          category: 'specific',
          data: item
        })
      }
    })
    
    // 🔥 方案3: 常见病虫害建议
    const commonPests = [
      { name: '小麦赤霉病', type: '病害', desc: '小麦常见真菌病害' },
      { name: '小麦锈病', type: '病害', desc: '小麦叶部病害' },
      { name: '小麦蚜虫', type: '虫害', desc: '小麦常见害虫' },
      { name: '玉米螟', type: '虫害', desc: '玉米茎秆害虫' },
      { name: '玉米大斑病', type: '病害', desc: '玉米叶部病害' },
      { name: '玉米褐斑病', type: '病害', desc: '玉米叶部病害' }
    ]
    
    commonPests.forEach(pest => {
      if (pest.name.toLowerCase().includes(keyword)) {
        suggestions.push({
          value: pest.name,
          type: pest.type,
          description: pest.desc,
          category: 'common'
        })
      }
    })
    
    // 🔥 方案4: 类型相关建议
    if (keyword.includes('病') || '病害'.includes(keyword)) {
      suggestions.push({
        value: '病害',
        type: '分类',
        description: '搜索所有病害信息',
        category: 'type'
      })
    }
    
    if (keyword.includes('虫') || '虫害'.includes(keyword)) {
      suggestions.push({
        value: '虫害',
        type: '分类',
        description: '搜索所有虫害信息',
        category: 'type'
      })
    }
    
    // 去重和排序
    const uniqueSuggestions = suggestions
      .filter((item, index, self) => 
        index === self.findIndex(t => t.value === item.value)
      )
      .slice(0, 8) // 最多显示8个建议
    
    console.log('🔍 生成搜索建议:', uniqueSuggestions.length, '个')
    callback(uniqueSuggestions)
    
  } catch (error) {
    console.error('获取搜索建议失败:', error)
    callback([])
  }
}

// 🔥 处理搜索建议选择
const handleSuggestionSelect = (item) => {
  console.log('🔍 选择搜索建议:', item)
  searchKeyword.value = item.value
  
  // 根据建议类型执行不同操作
  if (item.category === 'crop') {
    // 作物类型 - 切换到对应分类
    const cropName = item.value
    let targetCategoryId = null
    let targetMenuIndex = null
    
    Object.entries(categories.value).forEach(([id, categoryInfo]) => {
      if (categoryInfo.name.includes(cropName)) {
        targetCategoryId = id
        const groupName = cropName.includes('小麦') || cropName.includes('玉米') ? '禾本科' : '其他'
        targetMenuIndex = `${groupName}-${id}`
      }
    })
    
    if (targetCategoryId) {
      activeMenu.value = targetMenuIndex
      isSearchMode.value = false
      searchResults.value = []
      selectCategory(targetCategoryId)
      ElMessage.success(`已切换到${cropName}分类`)
    } else {
      handleSearch()
    }
  } else if (item.category === 'specific' && item.data) {
    // 具体病虫害 - 直接跳转到详情页
    goToSpecificDetail(item.data)
  } else {
    // 其他类型 - 执行搜索
    handleSearch()
  }
}

// 🔥 获取建议标签类型
const getSuggestionTagType = (type) => {
  const typeMap = {
    '作物': 'primary',
    '病害': 'danger',
    '虫害': 'warning',
    '生理性病害': 'info',
    '分类': 'success'
  }
  return typeMap[type] || 'info'
}

// 🔥 获取标签类型的方法
const getTagType = (type) => {
  switch (type) {
    case '病害':
      return 'danger'
    case '虫害':
      return 'warning'
    case '生理性病害':
      return 'info'
    default:
      return 'info'
  }
}

// 🔥 修复顶部菜单选择
const handleMenuItemSelect = (key) => {
  activeIndex.value = key;
  const routeName = routerList[key];
  if (routeName) {
    router.push({ name: routeName });
  }
};

// 设置搜索关键词并搜索
const setKeyword = (word) => {
  searchKeyword.value = word;
  handleSearch();
};

// 🔥 方法：加载作物分类
const loadCategories = async () => {
  try {
    categoriesLoading.value = true
    console.log('🔍 开始加载作物分类...')

    const response = await getPestDiseaseCategories()

    if (response.code === 200) {
      categories.value = response.data
      console.log('✅ 作物分类加载成功:', categories.value)

      // 🔥 处理路由参数
      await handleRouteParams()

    } else {
      console.error('❌ 加载作物分类失败:', response.msg)
      ElMessage.error('加载作物分类失败')
    }
  } catch (error) {
    console.error('💥 加载作物分类出错:', error)
    ElMessage.error('加载作物分类失败，请检查网络连接')
  } finally {
    categoriesLoading.value = false
  }
}

// 🔥 优化：处理路由参数
const handleRouteParams = async () => {
  const { crop, category, autoSearch } = route.query
  
  console.log('🔍 处理路由参数:', { crop, category, autoSearch })
  
  if (autoSearch === 'true' && crop && category) {
    console.log('🎯 检测到自动搜索请求')
    
    // 🔥 首先尝试找到对应的作物分类
    let targetCategoryId = null
    let targetMenuIndex = null
    
    Object.entries(categories.value).forEach(([id, categoryInfo]) => {
      if (categoryInfo.name.includes(crop)) {
        targetCategoryId = id
        const groupName = crop.includes('小麦') || crop.includes('玉米') ? '禾本科' : '其他'
        targetMenuIndex = `${groupName}-${id}`
      }
    })
    
    if (targetCategoryId) {
      console.log('✅ 找到目标分类:', targetCategoryId)
      
      // 设置活动菜单
      activeMenu.value = targetMenuIndex
      
      // 选择对应的分类
      await selectCategory(targetCategoryId)
      
      // 根据category类型进行过滤显示
      if (category === '病害') {
        ElMessage.success(`已切换到${crop}${category}分类`)
      } else if (category === '虫害') {
        ElMessage.success(`已切换到${crop}${category}分类`)
      } else {
        ElMessage.success(`已切换到${crop}分类`)
      }
      
      // 设置搜索关键词但不执行搜索，让用户看到分类数据
      searchKeyword.value = `${crop}${category}`
      
    } else {
      console.log('❌ 未找到对应分类，执行搜索')
      // 如果找不到分类，设置搜索关键词并执行搜索
      searchKeyword.value = `${crop}${category}`
      await handleSearch()
    }
  } else {
    // 🔥 默认选择第一个分类（小麦）
    const firstCategoryId = Object.keys(categories.value)[0]
    if (firstCategoryId) {
      console.log('🔧 加载默认分类:', firstCategoryId)
      await selectCategory(firstCategoryId)
    }
  }
}

// 🔥 方法：选择分类并加载数据
const selectCategory = async (categoryId) => {
  try {
    dataLoading.value = true
    currentCategoryId.value = categoryId

    const categoryInfo = categories.value[categoryId]
    if (categoryInfo) {
      currentCrop.value = categoryInfo.name
    }

    console.log('🔍 开始加载分类数据，分类ID:', categoryId)

    const response = await getPestDiseaseByCategory(categoryId)

    if (response.code === 200) {
      pestData.value = response.data
      console.log('✅ 分类数据加载成功:', pestData.value)

      // 退出搜索模式
      isSearchMode.value = false
      searchResults.value = []

    } else {
      console.error('❌ 加载分类数据失败:', response)
      ElMessage.error(response.msg || '加载数据失败')
    }
  } catch (error) {
    console.error('💥 加载分类数据出错:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
  } finally {
    dataLoading.value = false
  }
}

// 🔥 方法：处理菜单选择
const handleMenuSelect = (index) => {
  console.log('🔍 菜单选择:', index)
  activeMenu.value = index

  // 解析菜单索引获取分类ID
  const parts = index.split('-')
  if (parts.length >= 2) {
    const categoryId = parts[1]
    selectCategory(categoryId)
    
    // 获取分类名称用于提示
    const categoryInfo = categories.value[categoryId]
    if (categoryInfo) {
      ElMessage.success(`已选择: ${categoryInfo.name}`)
    }
  }
}

// 🔥 优化搜索功能 - 支持组合搜索和智能匹配
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词")
    return
  }

  try {
    searchLoading.value = true
    isSearchMode.value = true

    console.log('🔍 开始智能搜索:', searchKeyword.value)

    let searchResults_local = []

    // 🔥 方法1: 直接API搜索
    try {
      const response = await searchPestDisease(searchKeyword.value)
      if (response.code === 200 && response.data) {
        searchResults_local = response.data
        console.log('✅ API搜索结果:', searchResults_local.length)
      }
    } catch (error) {
      console.warn('API搜索失败，尝试本地搜索')
    }

    // 🔥 方法2: 如果API搜索无结果，尝试智能解析和本地搜索
    if (searchResults_local.length === 0) {
      console.log('🔍 API搜索无结果，开始智能本地搜索')
      
      const keyword = searchKeyword.value.toLowerCase().trim()
      
      // 识别作物类型
      let targetCrop = null
      if (keyword.includes('小麦')) {
        targetCrop = '小麦'
      } else if (keyword.includes('玉米')) {
        targetCrop = '玉米'
      }
      
      // 识别类型
      let targetType = null
      if (keyword.includes('病害')) {
        targetType = '病害'
      } else if (keyword.includes('虫害')) {
        targetType = '虫害'
      } else if (keyword.includes('生理') || keyword.includes('非生物')) {
        targetType = '生理性病害'
      }
      
      console.log('🔍 智能解析结果:', { targetCrop, targetType })
      
      // 如果识别出作物类型，尝试从对应分类中搜索
      if (targetCrop) {
        let targetCategoryId = null
        Object.entries(categories.value).forEach(([id, categoryInfo]) => {
          if (categoryInfo.name.includes(targetCrop)) {
            targetCategoryId = id
          }
        })
        
        if (targetCategoryId) {
          console.log('🔍 找到目标分类，加载数据进行本地搜索')
          try {
            const response = await getPestDiseaseByCategory(targetCategoryId)
            if (response.code === 200 && response.data) {
              const allData = [
                ...(response.data.diseases || []),
                ...(response.data.pests || []),
                ...(response.data.physiologicalDiseases || [])
              ]
              
              // 根据类型过滤
              if (targetType) {
                searchResults_local = allData.filter(item => 
                  item.type === targetType || 
                  (targetType === '生理性病害' && (item.type === '非生物胁迫' || item.type === '生理性病害'))
                )
              } else {
                // 如果没有指定类型，返回所有相关数据
                searchResults_local = allData
              }
              
              console.log('✅ 本地搜索结果:', searchResults_local.length)
            }
          } catch (error) {
            console.error('本地搜索失败:', error)
          }
        }
      }
    }

    // 🔥 方法3: 如果还是没有结果，尝试模糊匹配
    if (searchResults_local.length === 0) {
      console.log('🔍 尝试模糊匹配搜索')
      
      // 从所有已加载的数据中进行模糊搜索
      const allCurrentData = [
        ...diseaseList.value,
        ...pestList.value,
        ...physiologicalDiseaseList.value
      ]
      
      const keyword = searchKeyword.value.toLowerCase()
      searchResults_local = allCurrentData.filter(item => 
        item.name.toLowerCase().includes(keyword) ||
        item.type.toLowerCase().includes(keyword)
      )
      
      console.log('✅ 模糊匹配结果:', searchResults_local.length)
    }

    searchResults.value = searchResults_local
    
    if (searchResults.value.length > 0) {
      ElMessage.success(`找到 ${searchResults.value.length} 个相关结果`)
    } else {
      ElMessage.warning(`未找到与"${searchKeyword.value}"相关的结果，请尝试其他关键词`)
    }
    
  } catch (error) {
    console.error('💥 搜索出错:', error)
    ElMessage.error('搜索失败，请检查网络连接')
    searchResults.value = []
  } finally {
    searchLoading.value = false
  }
}

// 🔥 方法：清除搜索
const clearSearch = () => {
  isSearchMode.value = false
  searchResults.value = []
  searchKeyword.value = ''
  
  // 🔥 如果有当前分类，重新加载当前分类数据
  if (currentCategoryId.value) {
    selectCategory(currentCategoryId.value)
  }
  
  ElMessage.info('已清除搜索结果，返回分类浏览')
}

// 🔥 方法：跳转到详情页面
const goToSpecificDetail = (item) => {
  console.log('🔍 点击病虫害:', item)
  ElMessage.success(`正在查看${item.name}详情...`)

  try {
    router.push({
      path: '/pest-disease-detail',
      query: {
        name: item.name,
        type: item.type
      }
    })
  } catch (error) {
    console.error('💥 路由跳转失败:', error)
    ElMessage.error('页面跳转失败，请检查路由配置')
  }
}

// 🔥 生命周期：页面加载时获取数据
onMounted(async () => {
  console.log('🚀 象差百科页面已加载，开始初始化数据...')
  console.log('🔍 路由参数:', route.query)
  await loadCategories()
})

// 🔥 监听搜索关键词变化
watch(searchKeyword, (newVal, oldVal) => {
  console.log('🔍 搜索关键词变化:', { oldVal, newVal })
  
  if (newVal === '' && oldVal && oldVal.length > 0 && isSearchMode.value) {
    console.log('🧹 自动清除搜索模式')
    clearSearch()
  }
})

// 🔥 监听路由变化
watch(() => route.query, (newQuery, oldQuery) => {
  console.log('🔄 路由查询参数变化:', { oldQuery, newQuery })
  
  if (newQuery.autoSearch === 'true' && newQuery !== oldQuery) {
    console.log('🎯 检测到新的自动搜索请求')
    handleRouteParams()
  }
}, { deep: true })
</script>

<style scoped>
/* 🔥 修复：确保顶部导航栏布局与其他页面完全一致 */

/* 顶部导航栏样式 - padding调整为与其他页面一致 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px; /* 🔥 确保与其他页面padding一致 */
  height: 60px;
  background: linear-gradient(90deg, #1bbc9b, #17c2e6);
  color: #fff;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo-title {
  font-weight: bold;
  font-size: 22px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

/* 分类导航样式 - 与其他页面完全一致 */
.custom-menu {
  border-bottom: 1px solid #e0e0e0;
  padding: 0 30px; /* 🔥 确保与其他页面padding一致 */
  font-size: 16px;
}

/* 搜索区域样式 - 与其他页面完全一致 */
.search-section {
  text-align: center;
  padding: 30px 20px; /* 🔥 确保与其他页面padding一致 */
  background-color: #f9f9f9;
}

.headline {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

/* 🔥 确保搜索框尺寸与其他页面完全一致 */
.search-input {
  width: 60vw;
  height: 50px;
}

/* 🔥 新增：搜索建议下拉框样式优化 */
:deep(.el-autocomplete-suggestion) {
  max-height: 300px;
  overflow-y: auto;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-autocomplete-suggestion .el-scrollbar__view) {
  padding: 4px 0;
}

:deep(.el-autocomplete-suggestion li) {
  line-height: auto;
  padding: 10px 15px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

:deep(.el-autocomplete-suggestion li:last-child) {
  border-bottom: none;
}

:deep(.el-autocomplete-suggestion li:hover) {
  background-color: #f8f9fa;
}

:deep(.el-autocomplete-suggestion li.highlighted) {
  background-color: #e8f4fd;
}

.suggestion-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.suggestion-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.suggestion-name {
  font-weight: 500;
  color: #333;
  flex: 1;
  text-align: left;
}

.suggestion-desc {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
  text-align: left;
}

.hot-words {
  font-size: 14px;
  color: #666;
}

.hot-words .el-link {
  margin-left: 10px;
}

/* 主内容区域样式 */
.content-section {
  padding: 25px;
}

/* 左侧导航栏样式 */
.sidebar {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
  height: fit-content;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e8f4f8;
  background: linear-gradient(135deg, #f8fffe, #f0f9ff);
  border-radius: 12px 12px 0 0;
}

.sidebar-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.sidebar-menu {
  border-right: none;
}

.category-skeleton {
  padding: 20px;
}

.category-count {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

/* 右侧主内容区域样式 */
.main-content {
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
}

.content-wrapper {
  padding: 0;
}

/* 病害、虫害和生理性病害区域样式 */
.disease-section,
.pest-section,
.physiological-disease-section,
.search-results-section {
  margin-bottom: 40px;
}

.section-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clear-search {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 4px;
}

.clear-search:hover {
  color: #409eff;
}

.count-skeleton {
  width: 100px;
  height: 20px;
}

/* 病虫害网格布局 */
.pest-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-bottom: 30px;
}

.pest-item {
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #333;
  min-height: 45px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.pest-item:hover {
  background: #e8f4f8;
  border-color: #42b883;
  color: #42b883;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 184, 131, 0.2);
}

.pest-name {
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .custom-header {
    flex-direction: column;
    text-align: center;
    gap: 10px;
    height: auto;
    padding: 15px;
  }

  .custom-menu {
    padding: 0 15px;
    font-size: 14px;
  }

  .search-section {
    padding: 20px;
  }

  .search-input {
    width: 90vw;
    height: 45px;
  }

  .content-section {
    padding: 10px;
  }

  .content-section .el-row {
    flex-direction: column;
  }

  .sidebar {
    margin-bottom: 20px;
  }

  .main-content {
    margin-bottom: 20px;
    padding: 15px;
  }

  .pest-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
  }

  .pest-item {
    padding: 10px;
    font-size: 13px;
    min-height: 40px;
  }

  .section-header {
    font-size: 16px;
    margin-bottom: 15px;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>